//
//  CommunityViewController.m
//  Lovely Food
//
//  Created by Moonths on 15/12/1.
//  Copyright © 2015年 李经纬. All rights reserved.
//

#import "CommunityViewController.h"
#import "CommunityCell.h"
#import "CommunityModel.h"
#import "MessageViewController.h"
#import <AVOSCloud.h>
#import "UIImageView+WebCache.h"

@interface CommunityViewController ()

@property (nonatomic, strong)NSMutableArray * dataArray;

@end

@implementation CommunityViewController
-(NSMutableArray *)dataArray
{
    if (_dataArray == nil) {
        self.dataArray = [NSMutableArray array];
        
    }
    return _dataArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"社区";
    // 预估高度
    self.tableView.estimatedRowHeight = 100;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"发布" style:(UIBarButtonItemStyleDone) target:self action:@selector(sendAction:)];
    UINib *nib = [UINib nibWithNibName:@"CommunityCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:@"Community_Cell"];
    
    [self loadData];
    
}

// 获取所有的发表信息
- (void)loadData
{
    
    AVQuery *query = [AVQuery queryWithClassName:@"Yan31Message"];
    // 按照降序来排序
    [query orderByDescending:@"createdAt"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (error == nil) {
            self.dataArray = nil;
            self.dataArray = [query findObjects].mutableCopy;
            [self.tableView reloadData];
        }
    }];
    
}

- (void)sendAction:(UIBarButtonItem *)sender
{
    if ([AVUser currentUser] != nil) {
        // 转场
        MessageViewController *message = [[MessageViewController alloc] init];
        message.result = ^{
            [self loadData];
            
        };
        [self showViewController:message sender:nil];
    } else {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请先登录" message:@"登陆后进行操作" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *OKbutton = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:OKbutton];
        [self presentViewController:alert animated:YES completion:^{
            
        }];
        
    }
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//warning Incomplete implementation, return the number of rows
    return self.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CommunityCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Community_Cell" forIndexPath:indexPath];
    cell.headImage.layer.cornerRadius = cell.headImage.frame.size.height / 2;
    cell.headImage.layer.masksToBounds = YES;


    AVObject *post = self.dataArray[indexPath.row];
    cell.contentLabel.text = [post objectForKey:@"content"];
    
    cell.userNameLabel.text = [post objectForKey:@"pubUser"];
    
    NSDate *timeDate = [post objectForKey:@"pubTimestamp"];
    
    NSDateFormatter *formtter = [[NSDateFormatter alloc] init];
    
    [formtter setDateFormat:@"MM月d日 HH:mm:ss"];
    
    cell.timeLabel.text = [formtter stringFromDate:timeDate];
    
    
    AVQuery *query  = [AVQuery queryWithClassName:@"_User"];
    [query getObjectInBackgroundWithId:[post objectForKey:@"pubObjectId"] block:^(AVObject *object, NSError *error) {
        if (!error) {
            NSLog(@"成功");
            AVFile *imageFile = [object objectForKey:@"headImage"];
            NSLog(@"%@",imageFile.url);
            [cell.headImage sd_setImageWithURL:[NSURL URLWithString:imageFile.url] placeholderImage:[UIImage imageNamed:@"touxiang"]];

            
        } else {
            NSLog(@"%@", error);
        }
    }];
//   AVObject *object = [query getObjectWithId:[post objectForKey:@"pubObjectId"]];
//    AVFile *imageFile = [object objectForKey:@"headImage"];
//    NSLog(@"%@",imageFile.url);
//    [cell.headImage sd_setImageWithURL:[NSURL URLWithString:imageFile.url] placeholderImage:[UIImage imageNamed:@"touxiang"]];
    
    return cell;
}



//取消cell距离navigationBar的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
